<template>
  <div class="index-box" ref="index">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <div class="search" ref="search">
          <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent
            class="demo-form-inline" id="searchBox">
            <el-form-item prop="nickname">
                <el-input v-model="searchForm.nickname" clearable placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="telephone">
                <el-input v-model="searchForm.telephone" clearable placeholder="用户手机号"></el-input>
            </el-form-item>

            <el-form-item prop="idcardNumber">
                <el-input v-model="searchForm.idcardNumber" clearable placeholder="分享或推荐人手机号"></el-input>
            </el-form-item>
            <el-form-item prop="dictValue">
              <el-select filterable clearable v-model="searchForm.dictValue" placeholder="积分区间">
                <el-option :label="item.dictLabel" :value="item.dictValue" v-for="item in integralList"></el-option>
              </el-select>
            </el-form-item>
           <el-form-item prop="time">
             <el-date-picker v-model="time" type="daterange" align="right" unlink-panels range-separator="至"
               start-placeholder="开始兑换日期" end-placeholder="结束兑换日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
               :picker-options="pickerOptions">
             </el-date-picker>
           </el-form-item>
           <el-form-item prop="getIntegralTime">
             <el-date-picker v-model="getIntegralTime" type="daterange" align="right" unlink-panels range-separator="至"
               start-placeholder="积分获取开始日历" end-placeholder="积分获取结束日历" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
               :picker-options="pickerOptions">
             </el-date-picker>
           </el-form-item>
            <el-form-item class="clearfix">
              <el-button type="primary" @click="handleSearch()" icon="el-icon-search">搜索</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="actionBtn" ref="actionBtn">
          <div class="actionBtnLeft">
            <el-radio-group v-model="searchForm.userLevel" size="small" @change="handleSearch()">
              <el-radio-button >全部</el-radio-button>
              <el-radio-button :label="item.levelId" v-for="item in levelList">{{item.name}}</el-radio-button>
            </el-radio-group>
            <el-radio-group v-model="searchForm.pointsLevelId" size="small" @change="handleSearch()" style="margin-left:10px">
              <el-radio-button >全部</el-radio-button>
              <el-radio-button :label="item.id" v-for="item in pointsLevelList">{{item.name}}</el-radio-button>
            </el-radio-group>
           <el-button
             style="margin-left:10px"
             type="warning"
             icon="el-icon-download"
             size="small"
             :loading="btnLoading"
             v-has="'user:userIntegral:down'"
             @click="handleExport"
           >导出</el-button>
          </div>
          <div class="actionBtnRight">
              <MyRefresh></MyRefresh>
              <MyTableColumnSet :tableColumn.sync="tableColumn" :hideTableColumn.sync="hideTableColumn" :tableColumnType.sync="tableColumnType"></MyTableColumnSet>
          </div>
        </div>

        <div class="table" ref="table">
          <el-table :data="dataList" style="width: 100%" row-key="id" border :height="tableHeight" v-loading="loading"  @sort-change="handleTablechangeSort" stripe>
            <el-table-column type="selection" width="55" align="center"> </el-table-column>
            <el-table-column prop="customerId" label="编号" v-if="!hideTableColumn.includes('customerId')" align="center"></el-table-column>
            <el-table-column prop="name" label="用户头像" v-if="!hideTableColumn.includes('userface')" align="center">
              <template #default="scope">
                 <el-image :src="scope.row.userface" fit="fill" v-image-preview="scope.row.userface" class="img"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="用户ID" v-if="!hideTableColumn.includes('code')" align="center"></el-table-column>
            <el-table-column prop="nickname" label="用户名" v-if="!hideTableColumn.includes('nickname')" align="center"></el-table-column>
            <el-table-column prop="telephone" label="手机号" v-if="!hideTableColumn.includes('telephone')" align="center"></el-table-column>
            <el-table-column prop="leveName" label="会员等级" v-if="!hideTableColumn.includes('leveName')" align="center"></el-table-column>
            <el-table-column prop="name" label="标签" v-if="!hideTableColumn.includes('tagList')" align="center">
              <template slot-scope="scope">
                <MyTableTag :tagList="scope.row.tagList"/>
              </template>
            </el-table-column>
            <el-table-column prop="parentPhone" label="分享或推荐人手机号" v-if="!hideTableColumn.includes('idcardNumber')" align="center"></el-table-column>
            <el-table-column prop="pointsLevelName" label="积分等级" v-if="!hideTableColumn.includes('pointsLevelName')" align="center"></el-table-column>、
            <el-table-column prop="pointsTotal" label="总积分" v-if="!hideTableColumn.includes('pointsTotal')" align="center" sortable></el-table-column>
           <!-- <el-table-column prop="levelName" label="已用积分" v-if="!hideTableColumn.includes('pointsYes')" align="center">
              <template slot-scope="scope">
                 {{usableIntegral(scope.row)}}
              </template>
            </el-table-column> -->
            <el-table-column prop="pointsCurrent" label="可用积分" v-if="!hideTableColumn.includes('pointsCurrent')" align="center"></el-table-column>
            <el-table-column prop="gpExchangeNum" label="已兑换仟豆数" v-if="!hideTableColumn.includes('gpExchangeNum')" align="center"></el-table-column>
            <el-table-column prop="gpExchangeTime" label="最新兑换时间" v-if="!hideTableColumn.includes('time')" align="center">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.gpExchangeTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="操作" width="140" fixed="right">
              <template #default="scope">
                  <el-button
                    v-if="scope.row.pointsCurrent!='0'"
                    size="medium"
                    type="text"
                    icon="el-icon-money"
                    @click="hanleConversionApply(scope.row)"
                    v-has="'user:userIntegral:apply'"
                  >兑换申请</el-button>
                  <ExchangeRecord :id="scope.row.customerId" :statusRow="scope.row"  text="兑换记录"  v-has="'user:userIntegral:record'" ></ExchangeRecord>
                  <IntegralSource :id="scope.row.customerId" :statusRow="scope.row"  text="积分来源"  v-has="'user:userIntegral:source'" ></IntegralSource>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page" ref="page">
          <MyPagination
             v-show="total"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="dataInfo"
          />
        </div>
      </el-col>
    </el-row>

    <!-- /*兑换申请 */	 -->
    <el-dialog title="兑换申请" width="600px" v-dialogDrag :visible.sync="upMoneyVisible" @close="upMoneyVisible = false" :close-on-click-modal="false" >
      <el-form  label-position="right" :model="upMoney" :rules="upMoneyRules" ref="upMoney">
          <el-form-item label="手机号为:" label-width="175px">
            <span class="red">{{statusRow.telephone}}</span> 用户的积分兑换申请
          </el-form-item>
          <el-form-item label="可兑换积分:" label-width="175px">
            <span class="red">{{statusRow.pointsCurrent}}</span> 积分
          </el-form-item>
          <el-form-item label="兑换比例:" label-width="175px">
            <span class="red">{{subscriptionRatio}}:1</span>
          </el-form-item>

          <el-form-item label="兑换数量:" prop="value" label-width="175px" class="convertibilityNumber">
            <el-input v-model="upMoney.value" clearable placeholder="兑换数量" type="number" class="inputNumber" :max="statusRow.pointsCurrent"></el-input> 积分
          </el-form-item>
          <el-form-item label="兑换仟豆数:" prop="exchangeValue" label-width="175px">
            <el-input v-model="upMoney.exchangeValue" clearable  placeholder="兑换仟豆数" type="number" class="inputNumber" disabled ></el-input> 
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upMoneyVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleSubmitupMoney('upMoney')" size="small" :loading="userLoading">提交申请</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import common from '@/api/api';
  import {
    pointsQueryUserPointsList,pointsAdd,userPointsExport,getManageParameter,getAvailablePoints
  } from '@/api/getData'
  import option from '../../common/option.js';
  import ExchangeRecord from '../user/components/exchangeRecord';
  import IntegralSource from '../user/components/integralSource';
  export default {
    components: {
      ExchangeRecord,
      IntegralSource

    },
    data() {
      var checkIntegral = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('需要扣除积分不能为空'));
        }
        setTimeout(() => {
          if (Number(value) > this.statusRow.pointsCurrent) {
            callback(new Error('需要扣除积分必须小于等于'+this.statusRow.pointsCurrent));
          }else if (Number(value) % this.subscriptionRatio != 0) {
            callback(new Error('需要扣除积分必须是'+this.subscriptionRatio+'的倍数'));
          } else {
            this.upMoney.exchangeValue = Number(value) / this.subscriptionRatio;
            callback();
          }
        }, 300);
      };
      return {
        sta:true,
        loading: false,
        userLoading: false,
        btnLoading:false,
        userVisible:false,
        upMoneyVisible:false,
        exportLoading: false,
        pointsLevelList:[],//
        integralList:[],
        time:[],
        getIntegralTime:[],
        searchForm: {
          nickname:undefined,
          telephone:undefined,
          parentPhone:undefined,
          userLevel:undefined,
          pointsLevelId:undefined,
          dictValue:undefined,
          dictSort:undefined,
          orderByColumn:undefined,
          pageNum:1,
          pageSize:20,
        },
        levelList:[],
        tableColumn:[{/*自定义表格列*/
            name:'编号',
            value:'customerId'
        },{
            name:'用户头像',
            value:'userface'
        },{
            name:'用户ID',
            value:'code'
        },{
            name:'用户名',
            value:'nickname'
        },{
            name:'手机号',
            value:'telephone'
        },{
            name:'会员等级',
            value:'leveName'
        },{
            name:'标签',
            value:'tagList'
        },{
            name:'分享或推荐人手机号',
            value:'idcardNumber'
        },{
            name:'积分等级',
            value:'pointsLevelName'
        },{
            name:'总积分',
            value:'pointsTotal'
        },{
            name:'已用积分',
            value:'pointsCurrent'
        },{
            name:'可用积分',
            value:'totalYesIncome'
        },{
            name:'已兑换仟豆数',
            value:'gpExchangeNum'
        },{
            name:'最新兑换时间',
            value:'gpExchangeTime'
        }],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/
        tableHeight:0,//table 高度
        statusRow:{},
        dataList:[],
        total: 0,
        multipleSelection: '',
        dialogTitle: '',

        upMoney:{
          customerId:'',
          value:'',
          exchangeValue:''
        },
        upMoneyRules:{
          value: [{required: true,validator: checkIntegral,trigger: 'change'}],
          exchangeValue: [{required: true, message: '兑换仟豆数不能为空',trigger: 'blur'}],
        },
        subscriptionRatio:0,
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.dataInfo();
      this.getSelect();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight - this.$refs.actionBtn.offsetHeight - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      /** 表格排序 **/
      handleTablechangeSort (column, prop, order) {
         this.searchForm.orderByColumn =  column.prop;
        this.searchForm.isAsc = column.order;
        this.dataInfo();
      },
      /** 导出按钮操作 */
       handleExport() {
        let data = this.addDateRange(this.searchForm, this.time, 'gpExchangeTimeStart', 'gpExchangeTimeEnd');
        data = this.addDateRange(this.searchForm, this.getIntegralTime, 'getStartTime', 'getEndTime');
        data.dictSort = undefined;
        for(let i=0;i<this.integralList.length;i++){
          if(data.dictValue==this.integralList[i].dictValue){
            data.dictSort = this.integralList[i].dictSort;
          }
        }
         this.$modal.confirm('是否确认导出搜索数据项？').then(() => {
           this.btnLoading = true;
           return userPointsExport(data);
         }).then(response => {
           this.$download.name(response.msg);
           this.btnLoading = false;
         }).catch(() => {});
      },
      usableIntegral(row){
        if(row.pointsTotal){
          return row.pointsTotal - row.pointsCurrent
        }else{
          return 0;
        }
      },
      handleSearch(){
          this.searchForm.pageNum = 1;
          this.dataInfo();
      },
      resetSearch(){
        this.time = [];
        this.resetForm('searchForm');
        this.dataInfo();
      },
      async dataInfo() {
        try {
          let data = this.addDateRange(this.searchForm, this.time, 'gpExchangeTimeStart', 'gpExchangeTimeEnd');
          data = this.addDateRange(this.searchForm, this.getIntegralTime, 'getStartTime', 'getEndTime');
          data.dictSort = undefined;
          for(let i=0;i<this.integralList.length;i++){
            if(data.dictValue==this.integralList[i].dictValue){
              data.dictSort = this.integralList[i].dictSort;
            }
          }
          this.loading = true;
          const result = await pointsQueryUserPointsList(data);
          if (result.code == 200) {
            this.total = result.total;
            let data = result.rows;
            data.map(item=>{
              item.status = item.status+'';
            })
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      getSelect(){
        this.getCategoryDetails({categoryKey:'member_level_category'}).then(res=>{ this.levelList = res.data; });
        this.getCategoryDetails({categoryKey:'points_level_config'}).then(res=>{ this.pointsLevelList = res.data; });
        this.getSelectList('points_interval').then(res=>{ this.integralList = res.data; })
        getManageParameter().then((result) => {
            if (result.code == '200') {
              this.subscriptionRatio = Number(result.data.subscriptionRatio);
             }else{
                this.$message.error(result.message);
             }
         });

      },
      /*兑换申请*/
      hanleConversionApply(row){
        this.statusRow =  JSON.parse(JSON.stringify(row));
        getAvailablePoints({customerId:row.customerId}).then((res)=>{
          this.statusRow.pointsCurrent = res.data;
          this.upMoney.customerId = row.customerId;
          this.upMoney.value = '';
          this.upMoney.exchangeValue = '';
          this.upMoneyVisible = true;
        })

      },
      handleDelt(id){
          this.$confirm('您确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            lifeTestPaperupdateStatus({id:id}).then((result) => {
                  if (result.code == '200') {
                       this.dataInfo();
                       this.$message({
                           message: result.message,
                           type: 'success'
                         });
                   }else{
                      this.$message.error(result.message);
                   }
               });
          }).catch(() => {
              console.log(1);
          });
      },

      handleSubmitupMoney(formName) {
        /*提额申请*/
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.statusRow.usableUnionIncome<this.upMoney.money){
               this.$message.error('申请提取金额不能大于'+this.statusRow.usableUnionIncome);
              return;
            }
            this.userLoading = true;
            pointsAdd(this.upMoney).then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);
                this.upMoneyVisible = false;
                this.dataInfo();
              } else {
                this.$message.error(result.msg);
              }
              this.userLoading = false;
            });
          }
        })
      },

    }
  }
</script>

<style scoped lang="scss">
  .convertibilityNumber /deep/input[type="number"]::-webkit-inner-spin-button,
 .convertibilityNumbe /deep/input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none !important;
    margin: 0 !important;
  }
  .inputNumber{
    width:180px;
  }
  .el-table .el-dropdown-link{
      cursor: pointer;
      color: #61997A;
      margin-left: 5px;
  }
    .leftDialog{
      height:540px;
      overflow-y: auto;
    }
    .activeVerticalBox .activeItem{
      color:#61997A;
      cursor: pointer;
      margin: 0px;
      text-align: center;
      height:20px;
      line-height: 20px;
    }
    .activeVerticalBox .el-dropdown{
      display: flex;
      justify-content: center;
      color:#61997A;
      cursor: pointer;
    }
    .activeCheckedBox{
      border-top: 1px solid #ddd;
      padding:10px;
      height:52px;
      .el-tag{
        margin-right:10px;
      }
    }
    .rateBox /deep/ .el-rate__icon{
      margin-right: 0px;
    }
    .rateBox>p{
      margin: 0px;
    }
    .rateBox>p> /deep/ .el-rate{
      height:25px;
      line-height:25px;
      display:flex;
    }
    .rateBox>p> /deep/ .el-rate .el-rate__item{
      display:flex;
      align-items: center;
    }
    .rateBox .rateText{
      width:60px;
    }
    .rateBox .content{
      display: flex;
    }
    .rateBox .el-tooltip{
          width: 100px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
    }
</style>
